package com.csu.geo.service;

import static org.hamcrest.CoreMatchers.instanceOf;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.csu.geo.entity.NgccOrigPolygon;
import com.csu.geo.entity.OrigPolygon;
import com.csu.geo.repository.NgccOrigPolygonDao;

@Component
@Transactional
public class NgccOrigPolygonService {

	@Autowired
	private NgccOrigPolygonDao ngccOrigPolygonDao;
	@Autowired
	private EntityManagerFactory entityManagerFactory;

	public int setTaskID(NgccOrigPolygon ngccOrigPolygon) {
		String hql = "update NgccOrigPolygon as p set p.taskId=:taskid where p.id=:id";
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		Query query = entityManager.createQuery(hql);
		query.setParameter("taskid", ngccOrigPolygon.getTaskId());
		query.setParameter("id", ngccOrigPolygon.getId());
		entityManager.getTransaction().begin();
		int flag = query.executeUpdate();
		entityManager.getTransaction().commit();
		entityManager.close();
		return flag;
	}

	public int setEditID(NgccOrigPolygon ngccOrigPolygon) {
		String hql = "update ngccOrigPolygon as p set p.editerId=? where p.taskid=?";
		EntityManager entityManager = entityManagerFactory.createEntityManager();
        Query query=entityManager.createNativeQuery(hql);
        query.setParameter(0,ngccOrigPolygon.getEditerId());
        query.setParameter(1, ngccOrigPolygon.getTaskId());
        int flag=query.executeUpdate();
        entityManager.getTransaction().commit();
        entityManager.close();
		return flag;
	}
	
	/**
	 * 任務查詢
	 * @param taskid
	 * @return
	 */
	public List<NgccOrigPolygon> findByTaskID(int taskid){
		List<NgccOrigPolygon> polygons=new ArrayList<>();
		String hql="from NgccOrigPolygon ng where ng.taskId=:taskId";
		EntityManager entityManager=entityManagerFactory.createEntityManager();
		Query query=entityManager.createQuery(hql);
		
		query.setParameter("taskId",taskid);
		entityManager.getTransaction().begin();
		polygons=query.getResultList();
		entityManager.getTransaction().commit();
        entityManager.close();
		return polygons;
	}
	
	public  List<NgccOrigPolygon> findAll()
	{
		return ngccOrigPolygonDao.findAll();
	}
	
	public NgccOrigPolygon findById(Integer id)
	{
		return ngccOrigPolygonDao.findById(id);
	}
	
}
